/**
 * 
 */
package com.jf.core;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jf.handler.Handler;
import com.jf.plugin.wbcs.WbcsPlugin;
import com.wbcs.WbcsFacade;
import com.wbcs.config.Config;
import com.wbcs.system.WbcsResponse;
import com.wbcs.util.Consts;
import com.wbcs.util.Tools;

/**
 * @author hawkfly
 *
 */
public class WbcsHandler extends Handler {
	private static Log log=LogFactory.getLog(WbcsHandler.class);
	private WbcsServlet servlet = new WbcsServlet();
	private ServletContext servletConstext= Jbsf.me().getServletContext();
	/* (non-Javadoc)
	 * @see com.jf.handler.Handler#handle(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean[])
	 */
	@Override
	public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
		// TODO Auto-generated method stub
		int haswebroot = Config.webroot.length() - Config.showreport_url.indexOf(Config.webroot) - 1;
		if(haswebroot == -1){
			haswebroot = 0;
		}
		
		String showreport_url = Config.showreport_url.substring(haswebroot);//过滤标识，同servlet url-pattern
		log.info(target);
		boolean isUriRoute = false;
		for(String uri : ActionMapping.pageMapping.keySet()){
			if((target.endsWith("/")?target:target+"/").equals(uri)){
				request.setAttribute("PAGEID", ActionMapping.pageMapping.get(uri));
				isUriRoute = true;break;
			}
		}
		if (target.startsWith(showreport_url) || isUriRoute) {
			isHandled[0] = true;
			try {
				servlet.service(request, response);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			next.handle(target, request, response, isHandled);
		}
		
	}
	
	public WbcsServlet getWbcsServlet()
	{
		return servlet;
	}

	public class WbcsServlet extends HttpServlet{
		private static final long serialVersionUID=715456159702221404L;

	    @Override
		public void service(HttpServletRequest request,HttpServletResponse response)
	            throws ServletException,IOException
	    {
	    	response.setContentType("text/html;charset=UTF-8");
	        String contentType=request.getHeader("Content-type");
	        if(contentType!=null&&contentType.startsWith("multipart/"))
	        {
	            WbcsFacade.uploadFile(request,response);
	        }else
	        {
	            String action=Tools.getRequestValue(request,"ACTIONTYPE","");
	            if(action.equalsIgnoreCase("updateconfig"))
	            {
	            	WbcsPlugin.loadReportConfigFiles("updateconfig");
	                PrintWriter out=response.getWriter();
	                out.println("完成配置文件更新");
	            }else if(action.equalsIgnoreCase("invokeServerAction"))
	            {
	                String resultStr=WbcsFacade.invokeServerAction(request,response);
	                if(resultStr!=null&&!resultStr.trim().equals(""))
	                {
	                    PrintWriter out=response.getWriter();
	                    out.println(resultStr);
	                }
	            }else if(action.equalsIgnoreCase("download"))
	            {
	                WbcsFacade.downloadFile(request,response);
	            }else if(action.equalsIgnoreCase("GetFilterDataList"))
	            {
	                response.reset();
	                response.setContentType("text/xml;charset="+Config.encode);
	                StringBuffer sbuffer=new StringBuffer("<?xml version=\"1.0\" encoding=\""+Config.encode+"\"?><items>");
	                sbuffer.append(WbcsFacade.getFilterDataList(request,response));
	                sbuffer.append("</items>");
	                PrintWriter out=response.getWriter();
	                out.println(sbuffer.toString().trim());
	            }else if(action.equalsIgnoreCase("GetTypePromptDataList"))
	            {
	                response.reset();
	                response.setContentType("text/xml;charset="+Config.encode);
	                StringBuffer sbuffer=new StringBuffer("<?xml version=\"1.0\" encoding=\""+Config.encode+"\"?><items>");
	                sbuffer.append(WbcsFacade.getTypePromptDataList(request,response));
	                sbuffer.append("</items>");
	                PrintWriter out=response.getWriter();
	                out.println(sbuffer.toString().trim());
	            }else if(action.equalsIgnoreCase("GetSelectBoxDataList"))
	            {
	                response.reset();
	                response.setContentType("text/html;charset="+Config.encode);
	                String resultStr=WbcsFacade.getSelectBoxDataList(request,response);
	                PrintWriter out=response.getWriter();
	                out.print(resultStr);
	            }else if(action.equalsIgnoreCase(Consts.GETAUTOCOMPLETEDATA_ACTION))
	            {
	                PrintWriter out=response.getWriter();
	                out.print(WbcsFacade.getAutoCompleteColValues(request,response));
	            }else if(action.equalsIgnoreCase("ShowUploadFilePage"))
	            {//显示文件上传界面
	                PrintWriter out=response.getWriter();
	                out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset="+Config.encode+"\">");
	                WbcsFacade.showUploadFilePage(request,out,new WbcsResponse(response));
	            }else
	            {
	                String type=Tools.getRequestValue(request,Consts.DISPLAYTYPE_PARAMNAME,String.valueOf(Consts.DISPLAY_ON_PAGE));
	                int itype=Consts.DISPLAY_ON_PAGE;
	                try
	                {
	                    itype=Integer.parseInt(type);
	                }catch(NumberFormatException e)
	                {
	                    log.error("传入的显示类型"+type+"不合法",e);
	                }
	                if(itype==Consts.DISPLAY_ON_PRINT)
	                {
	                    WbcsFacade.printComponents(request,response);
	                }else if(itype==Consts.DISPLAY_ON_PLAINEXCEL)
	                {
	                    response.reset();
	                    response.setContentType("application/vnd.ms-excel;charset="+Config.encode);
	                    WbcsFacade.exportReportDataOnPlainExcel(request,response);
	                }else if(itype==Consts.DISPLAY_ON_RICHEXCEL)
	                {
	                    response.reset();
	                    response.setContentType("application/vnd.ms-excel;charset="+Config.encode);
	                    WbcsFacade.exportReportDataOnWordRichexcel(request,response,Consts.DISPLAY_ON_RICHEXCEL);
	                }else if(itype==Consts.DISPLAY_ON_WORD)
	                {
	                    response.reset();
	                    response.setContentType("application/vnd.ms-word;charset="+Config.encode);
	                    WbcsFacade.exportReportDataOnWordRichexcel(request,response,Consts.DISPLAY_ON_WORD);
	                }else if(itype==Consts.DISPLAY_ON_PDF)
	                {
	                    response.reset();
	                    response.setContentType("application/pdf;charset="+Config.encode);
	                    WbcsFacade.exportReportDataOnPDF(request,response,Consts.DISPLAY_ON_PDF);
	                    
	                }else
	                { 
	                    WbcsFacade.displayReport(request,response);
	                }
	            }
	        }
	    }
	}
}
